# _*_ coding: utf-8 _*_

from email.mime.text import MIMEText
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.nonmultipart import MIMENonMultipart
from email import encoders

import smtplib


class EmailOperate:

    def send_mail_with_file(self, filepath, filename, subject):
        """
        发送一个带有附件（测试报告）的邮件，邮件的配置项来自sysconfig
        :param filepath: 报告文件的路径
        :param filename: 报告文件的名称
        :param subject: 邮件标题
        :return: None
        """
        # 邮件对象
        msg = MIMENonMultipart()
        msg['From'] = "UIAutoTester"
        msg['To'] = "you"
        msg['Subject'] = Header(subject, 'utf-8').encode()

        # 邮件正文是MIMEText:
        msg.attach(MIMEText('请查收自动化测试结果,见附件', 'plain', 'utf-8'))

        # 添加附件
        with open(filepath, 'rb') as f:
            # 设置附件的MIME和文件名:
            mime = MIMEApplication(open(filepath, 'rb').read())
            # 加上必要的头部信息
            mime.add_header('Content-Disposition', 'attachment', filename=filename)
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-ID', '0')
            # 把附件的文件读进来
            mime.set_payload(f.read())
            # 用 Base64编码:
            encoders.encode_base64(mime)
            # 添加到MIMEMuitipart:
            msg.attach(mime)

        server = smtplib.SMTP(smtp_server, 587)
        server.starttls()
        server.set_debuglevel(1)
        server.login(from_addr, password)
        server.sendmail(from_addr, [to_addr], msg.as_string())
        server.quit()
